import React, { useEffect, useState } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { View, Input, Image, Button, Textarea } from '@tarojs/components';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import { observer } from 'mobx-react-lite';
import store from '@/src/store';
import LoadingSpinner from '@/src/components/loadingSpinner';
import { showToast, StatusToast } from '@/src/components/statusToast';
import { feedbackFun } from '@/src/common/method/userInfoFun';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';

const MAX_TITLE = 35;
const MAX_IMAGES = 2;
//意见反馈
const FoodeBack = () => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [images, setImages] = useState<string[]>([]);
  const [disable, setDisable] = useState<boolean>(true);
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  const handleChooseImage = async () => {
    const remain = MAX_IMAGES - images.length;
    if (remain <= 0) {
      showToast('最多只能选 2 张图片');
      return;
    }
    const res = await Taro.chooseImage({
      count: remain,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera', 'album'],
    });
    // 新拍照的图会排在最前面
    setImages((prev) => [...res.tempFilePaths, ...prev]);
  };

  const removeImage = (idx: number) => {
    setImages((prev) => prev.filter((_, i) => i !== idx));
  };
  //提交反馈
  const handleSubmit = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (disable) {
      Taro.showToast({ title: '请添加标题', icon: 'none' });
      return;
    }
    Taro.showToast({
      title: '提交中',
      icon: 'loading',
      duration: 1000,
    });
    const userId = Taro.getStorageSync('userId');
    //参数不存在则传空
    feedbackFun({
      title: title,
      content: content,
      creator: Taro.getStorageSync(`nickname-${userId}`),
      creatorPhone: Taro.getStorageSync('mobile'),
      photoUrls: images,
    }).then((res: any) => {
      showToast('提交成功', '', 10);
      //跳转到首页
      Taro.reLaunch({ url: '/pages/home/index' });
    });
  };

  useEffect(() => {
    if (title.length > 0) {
      setDisable(false);
    } else {
      setDisable(true);
    }
  }, [title]);
  return (
    <View
      className="feed-back-page"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      {/* 标题区 */}
      <TitleBar showLeftBack={true} title="意见反馈"></TitleBar>

      <View className="content-area">
        <Input
          className="title-input"
          placeholder="请添加标题"
          value={title}
          maxlength={MAX_TITLE}
          onInput={(e) => setTitle(e.detail.value)}
        />
        <Textarea
          className="text-input"
          value={content}
          adjustPosition={false}
          holdKeyboard
          maxlength={-1}
          placeholder="请具体描述您所遇到的问题，我们将及时跟进处理！"
          onInput={(e) => {
            const v = e.detail.value || '';
            setContent(v.length > 500 ? v.slice(0, 500) : v);
          }}
        />
        <View
          className="image-container"
          style={{ display: images.length > 0 ? 'flex' : 'block' }}
        >
          {images && images.length > 0 && (
            <View
              className="image-grid"
              style={{ width: images.length * 78 + 'px' }}
            >
              {images.map((img, i) => (
                <View className="image-cell" onClick={() => removeImage(i)}>
                  <Image src={img} className="cell"></Image>
                  <Image
                    src="https://file.linkcook.cn/image/wineMiniProgram/home/deletPng.png"
                    className="delete"
                  ></Image>
                </View>
              ))}
            </View>
          )}
          <Image
            onClick={handleChooseImage}
            src={
              'https://file.linkcook.cn/image/wineMiniProgram/mine/addPic.png'
            }
            className="bt-icon"
          ></Image>
        </View>
      </View>
      <Button
        className={`submit-btn submit-btn-${disable}`}
        onClick={() => handleSubmit()}
      >
        提交
      </Button>
      <LoadingSpinner text="" />
      <StatusToast />
    </View>
  );
};

export default observer(FoodeBack);
